/*
 * @Author: 肖思汗 
 * @Date: 2025-08-13 14:34:23 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-23 20:58:52
 */

import OSS from "ali-oss";
import path from "path";
import dotenv from 'dotenv';
import fs from 'fs';
// 修改 FC2 导入方式
const FC2 = require('@alicloud/fc2');

// 加载对应环境的env文件
dotenv.config({ path: '.env' });

// console.log("accessKeyId", process.env.accessKeyId);
// console.log("accessKeySecret", process.env.accessKeySecret);
// console.log("region", process.env.region);
// console.log("bucket", process.env.bucket);

// 递归读取文件夹内所有文件，包括子目录的文件
function walk(dir: string, fileList: Array<string> = []) {
    const files = fs.readdirSync(path.join(__dirname, dir));
    files.forEach((val: string) => {
        const info = fs.statSync(path.join(__dirname, dir, val));
        if (info.isFile()) {
            fileList.push(path.join(dir, val));
        }
        if (info.isDirectory()) {
            walk(path.join(dir, val), fileList);
        }
    })
    return fileList;
}


(async () => {

    // 1.配置 OSS 客户端
    const ossClient = new OSS({
        region: process.env.region,
        accessKeyId: process.env.accessKeyId || "",
        accessKeySecret: process.env.accessKeySecret || "",
        bucket: process.env.bucket,
    });

    console.log(`开始上传`);

    // 2.读取本地前端代码目录
    const localDir = path.join(__dirname, '../dist');
    const files = walk('../dist', [] as string[]);

    // 3.设置oss上的目录
    const ossDir = '/taro_vite_react_mobx_node_express_sequelize';

    for (const file of files) {
        const filePath = path.join(__dirname, file as string);
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            // 3. 上传文件到OSS
            let ossPath = path.join(__dirname, file as string).replace(/\\/g, '/');
            ossPath = ossPath.replace(localDir.replace(/\\/g, '/'), ossDir);
            await ossClient.put(ossPath, fs.createReadStream(filePath));
        }
    }

    const distServiceZip = path.join(__dirname, '../dist-service.zip');
    console.log("distServiceZip", distServiceZip);

    // await ossClient.put(
    //     path.join(ossDir, './dist-service.zip').replace(/\\/g, '/'),
    //     fs.createReadStream(distServiceZip)
    // );

    console.log(`上传完成`);

    // 开始云函数自动发版
    // try {
    //     console.log('开始更新云函数...');

    //     // 配置云函数客户端 - 确保传入有效的配置
    //     const fcConfig = {
    //         region: process.env.FC_REGION || '',
    //         accessKeyID: process.env.accessKeyId || '',
    //         accessKeySecret: process.env.accessKeySecret || '',
    //         accountId: process.env.FC_ACCOUNT_ID || '',
    //     };

    //     // 验证必要的配置参数
    //     if (!fcConfig.region || !fcConfig.accessKeyID || !fcConfig.accessKeySecret || !fcConfig.accountId) {
    //         throw new Error('云函数配置不完整，请检查 .env 文件中的 FC_REGION、accessKeyId、accessKeySecret 和 FC_ACCOUNT_ID');
    //     }

    //     const client = new FC2(fcConfig.accountId, fcConfig);
    //     var serviceName = '';
    //     var funcName = 'taro_vite_react_mobx_node_express_sequelize_service';

    //     client.UpdateService(serviceName).then((resp: any) => {
    //         console.log('create service: %j', resp);
    //         return client.createFunction(serviceName, {
    //             functionName: funcName,
    //             handler: 'index.handler',
    //             memorySize: 128,
    //             runtime: 'nodejs4.4',
    //             code: {
    //                 zipFile: fs.readFileSync('/tmp/index.zip', 'base64'),
    //             },
    //         });
    //     }).then((resp: any) => {
    //         console.log('create function: %j', resp);
    //         return client.invokeFunction(serviceName, funcName, 'event');
    //     }).then((resp: any) => {
    //         console.log('invoke function: %j', resp);
    //     }).catch((err: unknown) => {
    //         console.error(err);
    //     });

    //     // 原代码中 response 变量未定义，推测此处可能缺少相应逻辑，暂时移除该变量
    //     console.log('云函数更新成功:');
    // } catch (err) {
    //     console.error('云函数更新失败:', err);
    // }
})();